//
//  Util.swift
//  imgZipReName
//
//  Created by dfpo on 26/02/2022.
//

import Foundation
import AVFoundation
import AppKit
import Cocoa
public class xUtils {
    
    // 取字符串数组
    public static func getStrsFromUserDefaults(key: String?) -> [String] {
        guard let key = key else {
            return [String]()
        }
        if let strs = UserDefaults.standard.object(forKey: key) as? [String] {
            return strs
        }
        return [String]()
    }
    /// 存字符串数组
    public static func saveStrToStrArr(key:String?, saveStr:String?) -> [String] {
        guard let key = key, let saveStr = saveStr else {
            return [String]()
        }
        let usde = UserDefaults.standard
        // 是文件
        if var strs = usde.object(forKey: key) as? [String], !strs.isEmpty {
            if !strs.contains(saveStr) {
                strs.append(saveStr)
            }
            
            if let oldIdx = strs.firstIndex(of: saveStr) {
                strs.remove(at: oldIdx)
            }
            strs.insert(saveStr, at: 0)
            usde.set(strs, forKey:key)
            return strs
        }
        usde.set([saveStr], forKey: key)
        return [saveStr]
    }
    
    /// 文件夹存在不
    public    static func isFolderExists(_ folderPath: String) -> Bool {
        let fileManager = FileManager()
        var isDir: ObjCBool = false
        return fileManager.fileExists(atPath: folderPath, isDirectory: &isDir) && isDir.boolValue
    }
    /// 文件存在不
    public static func isFileExists(_ filePath: String) -> Bool {
        let fileManager = FileManager()
        var isDir: ObjCBool = false
        return fileManager.fileExists(atPath: filePath, isDirectory: &isDir) && !isDir.boolValue
    }
    /// 如果文件夹存在，就尝试删除这个文件夹
    public  static func removeFolderAtPath(_ folderPath: String) {
        if isFolderExists(folderPath) {
            do {
                try FileManager().removeItem(at: URL(fileURLWithPath: folderPath))
            } catch {
                print("删除文件夹失败：\(error)")
            }
        }
    }
    /// 如果文件夹不存在， 就尝试创建这个文件夹
    public  static func createFolder(_ folderPath: String) {
        if !isFolderExists(folderPath) {
            do {
                try FileManager().createDirectory(at: URL(fileURLWithPath: folderPath), withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("创建文件夹失败：\(error)")
            }
        }
    }
    
    
    /// 功能：选择文件夹
    /// - Parameters:
    ///   - directoryURL: 默认从哪个位置开始
    @MainActor public static func chooseFolder(for window: NSWindow?, directoryURL: URL? = nil, completionHandler handler: @escaping ((String) -> Void)) {
        guard let window = window else {
            return
        }
        
        
        let panel:NSOpenPanel = NSOpenPanel()
        panel.canChooseFiles = false
        panel.canChooseDirectories = true
        panel.allowsMultipleSelection = false
        panel.resolvesAliases = true
        if let directoryURL = directoryURL {
            panel.directoryURL = directoryURL
        }
        panel.beginSheetModal(for: window) { (response) in
            if response == .OK, let folderPath = panel.urls.first?.path, !folderPath.isEmpty {
                handler(folderPath)
            }
        }
        
    }
    /// 显示一个alert弹窗
    @MainActor public static func showAlter(msg: String?) {
        guard let msg = msg else {
            return
        }
        let alert = NSAlert()
        
        alert.messageText = ""
        
        alert.informativeText = msg
        
        alert.alertStyle = NSAlert.Style.warning
        
        alert.addButton(withTitle: "OK")
        
        alert.runModal()
    }
    /// 打开文件夹并选中文件/
    public static func openFolderAndSelectFile(at fileURL: URL) {
        let folderURL = fileURL.deletingLastPathComponent()
        
        // 使用 NSWorkspace 打开文件夹
        NSWorkspace.shared.open(folderURL)
        
        // 延迟一段时间，以确保文件夹已经打开
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            // 选中文件
            NSWorkspace.shared.activateFileViewerSelecting([fileURL])
        }
    }
    
    public static func convertMovToMp4(inputURL: URL, outputURL: URL, completion: @escaping (Error?) -> Void) {
        let asset = AVAsset(url: inputURL)
        guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else {
            completion(NSError(domain: "com.example", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"]))
            return
        }
        
        exportSession.outputURL = outputURL
        exportSession.outputFileType = .mp4
        
        exportSession.exportAsynchronously {
            switch exportSession.status {
            case .completed:
                completion(nil)
            case .failed:
                completion(exportSession.error)
            case .cancelled:
                completion(NSError(domain: "com.example", code: 0, userInfo: [NSLocalizedDescriptionKey: "Export cancelled"]))
            default:
                break
            }
        }
    }
    /// 从文件加载字符串
    public static func stringFromPath(_ logFilePath: String) -> String? {
        do {
            let file = try FileHandle(forReadingFrom: URL(fileURLWithPath: logFilePath))
            defer {
                file.closeFile()
            }
            var fileData = Data()
            let bufferSize = 1024
            
            while autoreleasepool(invoking: {
                let data = file.readData(ofLength: bufferSize)
                if data.isEmpty {
                    // 如果数据为空，表示文件已经读取完毕
                    return false
                }
                // 将读取的数据追加到总数据中
                fileData.append(data)
                return true
            }) {}
            
            // 将文件数据转换为字符串
            guard let logFileContent = String(data: fileData, encoding: .utf8) else {
                return "Error decoding log file content"
            }
            
            return logFileContent
            
        } catch {
            return "Error reading log file: \(error)"
        }
    }
}
